package com.example.longpolling;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @author denis.huang
 * @since 2018/10/20 09:45
 */
@RestController
@RequestMapping("/test")
public class LongPollingController {
  private Logger logger = LoggerFactory.getLogger(LongPollingController.class);

  @Autowired
  private MsgService msgService;

  @RequestMapping("/callable")
  public Callable<String> test() {
    logger.info("Request received");
    Callable<String> callable = () -> {
      try {
        TimeUnit.SECONDS.sleep(15);
      } catch (Exception e) {
        // do nothing
      }
      logger.info("return");
      return "hello world";
    };
    logger.info("end callable");

    return callable;
  }

  @RequestMapping("/pull")
  public DeferredResult<String> test1(String key) {
    logger.info("Request received");

    DeferredResult<String> dr = new DeferredResult<>(30 * 1000L, "time out");
    dr.onCompletion(() -> msgService.remove(key));

    try {
      msgService.add(key, dr);
    } catch (Exception e) {
      dr.setErrorResult("error");
    }

    return dr;
  }

  @RequestMapping("send")
  public String send(String key, String msg) {
    msgService.send(key, msg);
    return "ok";
  }
}
